﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Data;
using System.Data.SqlClient;

public partial class UserControl_ControlPages : System.Web.UI.UserControl
{

    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    ClassExecute.ClassExecute dt;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // From tab input
            ThreadStart ths1 = new ThreadStart(GetMenuList);
            Thread th1 = new Thread(ths1);
            th1.Start();
            th1.Join();

            ThreadStart ths2 = new ThreadStart(GetLanguageList);
            Thread th2 = new Thread(ths2);
            th2.Start();
            th2.Join();

            // From tab search
            ThreadStart ths3 = new ThreadStart(GetMenu2List);
            Thread th3 = new Thread(ths3);
            th3.Start();
            th3.Join();

            ClearAdd();

        }
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        ClearAdd();
    }

    private void ClearAdd()
    {
        TabContainer1.ActiveTabIndex = 0;
        txtPageName.Text = "";
        txtUrl.Text = "";

        ViewState["flag"] = true;
        txtPageName.Focus();

        btnSave.Text = Resources.LanguageResource.Save;
        lblMsg.Text = "";
        lblMsg.Visible = false;
    }


    private void GetMenuList()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "n_Menu_GetAll", CommandType.StoredProcedure,
            new SqlParameter("@LanguageName", Session["lang"]));
        dt.BindDropDownList(db, ddlMenu, "MenuID", "MenuName");
    }

    private void GetMenu2List()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "n_Menu_GetMenuList", CommandType.StoredProcedure,
            new SqlParameter("@LanguageName", Session["lang"]));
        dt.BindDropDownList(db, ddlMenu2, "MenuID", "MenuName");
    }
    private void GetLanguageList()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "n_Language_GetAll", CommandType.StoredProcedure);
        dt.BindDropDownList(db, ddlLanguage, "ID", "FullName");
        ddlLanguage.SelectedValue = "1";
        ddlLanguage.Enabled = false;
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        if (Page.IsValid)
        {
            try
            {
                if ((bool)ViewState["flag"])
                {
                    #region Thêm một page mới
                    // thêm vào bảng pages và pagelanguage
                    int rel = dt.ExecuteSQl_int(str, "n_Pages_Insert", CommandType.StoredProcedure, ref error,
                        new SqlParameter("@MenuID", ddlMenu.SelectedValue),
                        new SqlParameter("@PageName", txtPageName.Text.Trim()),
                        new SqlParameter("@PageUrl", txtUrl.Text.Trim())
                        );
                    switch (rel)
                    {
                        case 1:
                            ClearAdd();
                            lblMsg.Text = Resources.LanguageResource.AddPageSuccessfully;
                            lblMsg.Visible = true;
                            break;
                        case 2:
                            lblMsg.Text = Resources.LanguageResource.AddPageFailed;
                            lblMsg.Visible = true;
                            break;
                        case 3:
                            lblMsg.Text = Resources.LanguageResource.AddPageFailedExist;
                            lblMsg.Visible = true;
                            break;
                        default:
                            break;
                    }
                }
                #endregion
                #region sửa thông tin page
                else
                {
                    int rel = dt.ExecuteSQl_int(str, "n_Pages_Update", CommandType.StoredProcedure, ref error,
                        new SqlParameter("@MenuID", ddlMenu.SelectedValue),
                        new SqlParameter("@PageName", txtPageName.Text.Trim()),
                        new SqlParameter("@PageUrl", txtUrl.Text.Trim()),
                        new SqlParameter("@LanguageID", ddlLanguage.SelectedValue),
                        new SqlParameter("@PageID", lblID.Text)
                        );
                    if (rel == 1)
                    {
                        lblMsg.Text = Resources.LanguageResource.UpdateSuccessfully;
                        lblMsg.Visible = true;
                    }
                    else
                    {
                        lblMsg.Text = Resources.LanguageResource.UpdateFailed;
                        lblMsg.Visible = true;
                    }
                     

                }
                #endregion
            }
            catch (Exception ex)
            {

                string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
            }
                    
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        BindGridSearch();
    }

    private void BindGridSearch()
    {
        // ngôn ngữ đang sử dụng
        string selectedLanguage = Session["lang"].ToString();

        // load
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "[n_Pages_Find]", CommandType.StoredProcedure,
            new SqlParameter("@parameter", txtSearch.Text),
            new SqlParameter("@menuID", ddlMenu2.SelectedValue),
            new SqlParameter("@languageName", selectedLanguage)
            );

        if (db.Rows.Count > 0)
        {
            grvPages.DataSource = db;
        }
        else
        {
            grvPages.DataSource = null;
        }
        grvPages.DataBind();
    }
    protected void grvUser_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                
                ddlLanguage.Enabled = true;
                ddlLanguage.SelectedIndex = 0;
              

                Label lblPageID = (Label)grv.FindControl("lblPageID");
                lblID.Text = lblPageID.Text;
                DataTable db = dt.Get_Data_DataTable(str, ref error, "[n_Pages_GetByPageID]", CommandType.StoredProcedure,
                    new SqlParameter("@PageID", lblPageID.Text),
                    new SqlParameter("@LanguageID", ddlLanguage.SelectedValue));

                
                txtPageName.Text = db.Rows[0]["PageName"].ToString();
                txtUrl.Text = db.Rows[0]["PageUrl"].ToString();


                ViewState["flag"] = false;
                btnSave.Text = Resources.LanguageResource.Edit;                
                lblMsg.Text = "";
                lblMsg.Visible = false;
                TabContainer1.ActiveTabIndex = 0;
                grvPages.DataSource = null;
                grvPages.DataBind();
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvUser_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {

        grvPages.PageIndex = e.NewPageIndex;
        BindGridSearch();
    }
    protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            dt = new ClassExecute.ClassExecute();
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[n_Pages_GetByPageID]", CommandType.StoredProcedure,
                        new SqlParameter("@PageID", lblID.Text),
                        new SqlParameter("@LanguageID", ddlLanguage.SelectedValue));

            txtPageName.Text = db.Rows[0]["PageName"].ToString();
            txtUrl.Text = db.Rows[0]["PageUrl"].ToString();
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
}